Creating simple aplication using Node.js, Express and PostgreSQL.

Installation Node.js

Windows:

In order to start, go to the download page Node.js (https://nodejs.org/en/download/). Select the installer that you want to download and install.

After we run the installer and complete the installation step-by-step.

CentOS:

To install Node.js, you need to connect to the server using the SSH protocol. After that, you need to install the latest version of .nodejs from the repositories. For this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ yum update

// Install the Development Tools group
$ yum -y groupinstall "Development Tools"

// Enter the command to connect to the server and create several concurrent sessions
$ yum -y install screen

// Go to /usr/src and load the archive with Node.js
$ cd / usr / src
$ wget http://nodejs.org/dist/v0.10.4/node-v0.10.4.tar.gz

// Extract the files from the archive and put them in the directory
$ tar zxf node-v0.10.4.tar.gz
$ cd node-v0.10.4

// Create the installation file and run it
$ make
$ make install

Node.js is installed. By default, its binary code is in /usr/local/bin/node.

Ubuntu

To install Node and npm via apt-get, run these commands:

1
2
3
4
sudo apt-get update  
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm

If you still want to use apt-get, but need a much newer version of Node, you should use this method.

This is very similar to the last one I showed you, but instead we’ll be running a script (maintained and distributed by NodeSource) to show the package manager where to get the latest version.

1
2
3
4
5
6
7
8

curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node

```

To verify that you have *Node.js* installed and check the version, run:

$ node –version

1
2

To start, run:

$ node

1
2
3
4
5


### Setting dependencies.

You can interactively generate the * package.json * file with the * npm init * command in the terminal.

$ npm init

1
2
3
4

After running the command you will be asked to enter some data. After you receive them * package.json * will be automatically generated and placed in the folder of your application.

If any dependencies are not installed, you can add them to your application with the following command:

npm install[module name] –save

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


### PostgreSQL installing.

PostgreSQL is a very popular database server, so it is present in official Ubuntu repositories.

**Windows**

You can download PostgreSQL from the official site download page here - http://www.postgresql.org/download/windows/

Download the installer by selecting a version suitable for the system capacity and following the steps offered by the installer.

**CentOS**

To install the latest version, add the official repository with the following command:

$ sudo rpm -Uvh http://yum.postgresql.org/9.5/redhat/rhel-7-x86_64/pgdg-centos95-9.5-2.noarch.rpm

1
2
After the repository is added to your system, you can proceed to install the program.
The installation of Postgresql CentOS is performed by the command:

$ sudo yum install postgresql96-server postgresql96

1
2

Immediately after installing Postgresql, the server is not yet ready for use, you need to initialize the necessary databases. To do this, execute:

$ /usr/pgsql-9.6/bin/postgresql96-setup initdb

1
2
3
4
5
6
7


**Ubuntu**

However, in PPA developers PostgreSQL you can find the latest version.

Add the PostgreSQL repository to the system source list:

$ sudo sh -c ‘echo “deb http://apt.postgresql.org/pub/repos/apt/ lsb_release -cs-pgdg main” >> /etc/apt/sources.list.d/pgdg.list’

1
2

and a key:

$ wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add -

1
2

This will allow you to receive the most recent versions when upgrading packages.

initdb -U postgres -D data
pg_ctl -D data start
psql -U postgres

1
2
3
4
5

Here *postgres* is the user name, it's better to specify it by default, for starters, and *data* is the directory where databases will be stored, you can specify any convenient.
After that *pg_ctl* starts PostgreSQL (indicating the directory with the databases).

At the end, we should see a welcome console:

postgres=#

1
2
3
4

### Express installing.

To install Express and add it to the dependency list, you must go to the project folder and run the command:

$ npm install express –save

1
2
3
4

### Creating a simple server application.

Create the directory where your project will be stored.

$ mkdir nodejs-express-postgresql/
$ cd nodejs-express-postgresql/

1
2

Now we need to initialize our application:

$ npm init -y

1
2
3
4

This command will create * package.json * with standard configuration settings.

Now create a file with our application.

$ touch app.js

1
2

Now you need to connect and configure Express.

const express = require(‘express’);
const bodyParser = require(‘body-parser’);

// Set up the express app
const app = express();

// Setup a default catch-all route that sends back a welcome message in JSON format.
app.get(‘*’, (req, res) => res.status(200).send({
message: ‘Welcome, my frined.’,
}));

module.exports = app;

1
2

Now if we run our server

npm run start:dev

1
2
3
4
5
6
7

And go to http://localhost:8000/, then we will see the message *Welcome, my friend.*

Now you need to connect our database.
We will immediately use the pool, not separate connections. This is a common practice, especially for PostgreSQL. The pool allows you to store multiple connections, thus not wasting time creating them and not dealing with their management.

First, configure the dependency, then add the connection to our database.

const Pool = require(‘pg’).Pool;

1
2

By default, *PostgreSQL* does not have a password, and the standard port is 5432.

const config = {
user: ‘postgres’,
host: ‘localhost’,
database: ‘users’,
password: ‘’,

};

const pool = new Pool(config);

1
2

Now it only remains to make our function, which will show all entries from the table *users*.

(async () => {
const client = await pool.connect()
try {
const res = await pool.query(“select * from users”);
console.log(res.rows[0])
} finally {
client.release()
}
})().catch(e => console.log(e.stack))

```

Now when you reboot our server you can see the result.

PostgreSQL:
https://node-postgres.com/
http://expressjs.com/ru/guide/database-integration.html

Node.js:
https://nodejs.org/en/
https://medium.com/devschacht/node-hero-chapter-1-239f7afeb1d1
https://node-postgres.com/features/pooling

Express:
http://expressjs.com/ru/

NPM:
https://www.npmjs.com/